/**
 * Created by zhangxiaoyu on 16/12/06.
 */
angular.module('hyt.addOrderCtrl',[])

  .controller('AddOrderCtrl',function($scope,$filter,$ionicModal,Storage,AddOrder,$ionicPopup,PaymentMethod,DeptByDivision,$ionicLoading,$timeout,$state,PackType,$stateParams,DefaultAddress,$ionicActionSheet,$cordovaCamera,$cordovaImagePicker,$window){
    var loginMsg=Storage.get('user');
    var userMsg=Storage.get('loginResult');
    $scope.order={
      customerId:userMsg.rows.id, //用户id
      belongId:$stateParams.companyId, //物流公司id
      companyName:$stateParams.companyName,
      orderId:'', //订单ID，为空是新增订单，不为空是编辑订单
      orderType:'0',
      consignorName:'', //发货人姓名
      consignorPhone:'', //发货人电话
      consignorProvince:'',//发货人省id
      consignorCity:'',//发货人市id
      consignorDistrict:'',//发货人区id
      consignorAddress:'', //发货人地址
      consignorDetailAddress:'',//发货人详细地址
      consigneeName:'', //收货人名称
      consigneePhone:'', //收货人电话
      consigneeProvince:'',//收货人省id
      consigneeCity:'',//收货人市id
      consigneeDistrict:'',//收货人区id
      consigneeAddress:'', //收货人地址
      consigneeDetailAddress:'',//收货人详细地址
      deliveryType:'', //送货方式
      paymentSwitch:'', //付款方式
      receiptSwitch:'', //是否签回单
      isReceipt:'',
      pickupSwitch:'', //是否提货
      isPickup:'',
      insureSwitch:'', //是否投保
      isInsure:'',
      remark:'', //备注
      pictureInfo:[],
      costMap:{
        AGENCY_FUND:'', //代收货款
        DECLARE_VALUE:'' //声明价值
      },
      goodsInfo:{
        goodsName:'', //货物名称
        pieces:'', //件数
        weight:'', //重量
        volume:'', //体积
        goodsPack:'' //包装
      },
      userMsg:{
        username:loginMsg.username,
        password:loginMsg.password,
        uuid:loginMsg.uuid
      }
    };
    if (Storage.get('addOrder')!=null){
      $scope.order=Storage.get('addOrder');
      $timeout(function(){
        $('#GOODS_PACK').val($scope.order.goodsInfo.goodsPack);
        $('#DELIVERY_TYPE').val($scope.order.deliveryType);
        $('#paymentMethod').val($scope.order.paymentSwitch);
        $('#weight').val(parseFloat($scope.order.goodsInfo.weight).toFixed(2));
        $('#volume').val(parseFloat($scope.order.goodsInfo.volume).toFixed(2));
        $('#AGENCY_FUND').val(parseFloat($scope.order.costMap.AGENCY_FUND).toFixed(2));
        $('#DECLARE_VALUE').val(parseFloat($scope.order.costMap.DECLARE_VALUE).toFixed(2));
      },300);
    }
    $(".twoDot").on("blur",function(){
      $(this).val(parseFloat($(this).val()).toFixed(2));
    });
    //默认收发地址
    var defaultAddress={
      customerId:userMsg.rows.id,
      userMsg:{
        username:loginMsg.username,
        password:loginMsg.password,
        uuid:loginMsg.uuid
      }
    };
    DefaultAddress.getDefaultAddress(JSON.stringify(defaultAddress));
    $scope.$on('DefaultAddress.Updated', function() {
      var result=DefaultAddress.getResult();
      if (result.success==true){
        $scope.defaultAddress=result.rows;
        if ($scope.defaultAddress.consigNee!=null){
          if (Storage.get('receiveAddress')==null){
            $scope.order.consigneeName=$scope.defaultAddress.consigNee.CUSTOMER_NAME;
            $scope.order.consigneePhone=$scope.defaultAddress.consigNee.CUSTOMER_PHONE;
            $scope.order.consigneeProvince=$scope.defaultAddress.consigNee.CONSIGNEE_PROVINCE;
            $scope.order.consigneeCity=$scope.defaultAddress.consigNee.CONSIGNEE_CITY;
            $scope.order.consigneeDistrict=$scope.defaultAddress.consigNee.CONSIGNEE_DISTRICT;
            $scope.order.consigneeAddress=$scope.defaultAddress.consigNee.CUSTOMER_ADDRESS;
            $scope.order.consigneeDetailAddress=$scope.defaultAddress.consigNee.CONSIGNEE_PROVINCE_NAME+$scope.defaultAddress.consigNee.CONSIGNEE_CITY_NAME+$scope.defaultAddress.consigNee.CONSIGNEE_DISTRICT_NAME+$scope.defaultAddress.consigNee.CUSTOMER_ADDRESS;
          }else {
            var receiveAddress=JSON.parse(Storage.get('receiveAddress'));
            $scope.order.consigneeName=receiveAddress.CUSTOMER_NAME;
            $scope.order.consigneePhone=receiveAddress.CUSTOMER_PHONE;
            $scope.order.consigneeProvince=receiveAddress.CONSIGNEE_PROVINCE;
            $scope.order.consigneeCity=receiveAddress.CONSIGNEE_CITY;
            $scope.order.consigneeDistrict=receiveAddress.CONSIGNEE_DISTRICT;
            $scope.order.consigneeAddress=receiveAddress.CUSTOMER_ADDRESS;
            $scope.order.consigneeDetailAddress=receiveAddress.CONSIGNEE_PROVINCE_NAME+receiveAddress.CONSIGNEE_CITY_NAME+receiveAddress.CONSIGNEE_DISTRICT_NAME+receiveAddress.CUSTOMER_ADDRESS;
          }
        }
        if ($scope.defaultAddress.shipper!=null){
          if (Storage.get('shippingAddress')==null){
            $scope.order.consignorName=$scope.defaultAddress.shipper.CUSTOMER_NAME;
            $scope.order.consignorPhone=$scope.defaultAddress.shipper.CUSTOMER_PHONE;
            $scope.order.consignorProvince=$scope.defaultAddress.shipper.CONSIGNEE_PROVINCE;
            $scope.order.consignorCity=$scope.defaultAddress.shipper.CONSIGNEE_CITY;
            $scope.order.consignorDistrict=$scope.defaultAddress.shipper.CONSIGNEE_DISTRICT;
            $scope.order.consignorAddress=$scope.defaultAddress.shipper.CUSTOMER_ADDRESS;
            $scope.order.consignorDetailAddress=$scope.defaultAddress.shipper.CONSIGNEE_PROVINCE_NAME+$scope.defaultAddress.shipper.CONSIGNEE_CITY_NAME+$scope.defaultAddress.shipper.CONSIGNEE_DISTRICT_NAME+$scope.defaultAddress.shipper.CUSTOMER_ADDRESS;
          }else {
            var shipperAddress=JSON.parse(Storage.get('shippingAddress'));
            $scope.order.consignorName=shipperAddress.CUSTOMER_NAME;
            $scope.order.consignorPhone=shipperAddress.CUSTOMER_PHONE;
            $scope.order.consignorProvince=shipperAddress.CONSIGNEE_PROVINCE;
            $scope.order.consignorCity=shipperAddress.CONSIGNEE_CITY;
            $scope.order.consignorDistrict=shipperAddress.CONSIGNEE_DISTRICT;
            $scope.order.consignorAddress=shipperAddress.CUSTOMER_ADDRESS;
            $scope.order.consignorDetailAddress=shipperAddress.CONSIGNEE_PROVINCE_NAME+shipperAddress.CONSIGNEE_CITY_NAME+shipperAddress.CONSIGNEE_DISTRICT_NAME+shipperAddress.CUSTOMER_ADDRESS;
          }
        }
      }
    });
    $scope.goChooseReceive=function(){
      $state.go('receiveAddress',{isChoose:1,htmlId:0});
      $scope.order.goodsInfo.goodsPack=$("#GOODS_PACK option:selected").val();
      $scope.order.deliveryType=$("#DELIVERY_TYPE option:selected").val();
      $scope.order.paymentSwitch=$("#paymentMethod option:selected").val();
      $timeout(function(){
        Storage.set('addOrder',$scope.order);
      },160);
    };
    $scope.goChooseShipper=function(){
      $state.go('shipperAddress',{isChoose:1,htmlId:0});
      $scope.order.goodsInfo.goodsPack=$("#GOODS_PACK option:selected").val();
      $scope.order.deliveryType=$("#DELIVERY_TYPE option:selected").val();
      $scope.order.paymentSwitch=$("#paymentMethod option:selected").val();
      $timeout(function(){
        Storage.set('addOrder',$scope.order);
      },160);
    };
    //物流公司
    $scope.showloading=true;
    $scope.companySearch={
      province:Storage.get('gpsProvince'),
      city:Storage.get('gpsCity'),
      county:Storage.get('gpsArea'),
      company_name:'',
      userMsg:{
        username:loginMsg.username,
        password:loginMsg.password,
        uuid:loginMsg.uuid
      }
    };
    DeptByDivision.getDeptByDivision(JSON.stringify($scope.companySearch));
    document.onkeydown=function(event){
      if(event.keyCode==13&&$scope.companySearch.company_name!=''){
        DeptByDivision.getDeptByDivision(JSON.stringify($scope.companySearch));
      }else {

      }
    };
    $scope.$on('DeptByDivision.Updated', function() {
      $scope.companyData=DeptByDivision.getResult().rows;
      $scope.showloading=false;
    });
    //下拉刷新
    $scope.doRefresh=function(){
      DeptByDivision.getDeptByDivision(JSON.stringify($scope.companySearch));
      $scope.$broadcast('scroll.refreshComplete');
    };
    $ionicModal.fromTemplateUrl('templates/tab-workbench/addOrder/chooseCompany.html', {
      scope: $scope
    }).then(function(modal) {
      $scope.modal = modal;
    });
    $scope.chooseComp=function(id,companyName){
      $scope.order.belongId=id;
      $scope.order.companyName=companyName;
      $scope.modal.hide();
    };
    //付款方式
    var paymentMethod={
      type:'payment_method',
      username:loginMsg.username,
      password:loginMsg.password,
      uuid:loginMsg.uuid
    };
    PaymentMethod.getPaymentMethod(JSON.stringify(paymentMethod));
    $scope.$on('PaymentMethod.Updated', function() {
      var result=PaymentMethod.getResult();
      if (result.success==true){
        $scope.paymentMethods=result.rows;
        Storage.set('paymentMethods',$scope.paymentMethods);
      }
    });
    //包装方式
    var packType={
      type:'pack_type',
      username:loginMsg.username,
      password:loginMsg.password,
      uuid:loginMsg.uuid
    };
    PackType.getPackType(JSON.stringify(packType));
    $scope.$on('PackType.Updated', function() {
      var result=PackType.getResult();
      if (result.success==true){
        $scope.packTypes=result.rows;
        Storage.set('packTypes',$scope.packTypes);
      }
    });
    //图片上传
    var imgPic=[];
    $scope.imgData=[];
    $scope.actionSheet=function(){
      var hideSheet = $ionicActionSheet.show({
        buttons: [
          { text: '拍照' },
          { text: '从相册选择' }
        ],
        cancelText: '取消',
        cancel: function() {
          // add cancel code..
        },
        buttonClicked: function(index) {
          if(index==0){
            var options = {
              destinationType: Camera.DestinationType.NATIVE_URI,
              sourceType: Camera.PictureSourceType.CAMERA,
              targetWidth: 800,
              targetHeight: 800
            };

            $cordovaCamera.getPicture(options).then(function(imageURI) {
              if (imgPic.length>2){
                $ionicLoading.show({
                  noBackdrop: true,
                  template: "最多支持三张照片",
                  duration: 1500
                });
              }else {
                imgPic[imgPic.length]= imageURI;
              }
            }, function(err) {
              // error
            });
          }else if (index==1){
            var options = {
              maximumImagesCount: 10,
              width: 800,
              height: 800,
              quality: 80
            };

            $cordovaImagePicker.getPictures(options)
              .then(function (results) {
                if (imgPic.length+results.length>3){
                  $ionicLoading.show({
                    noBackdrop: true,
                    template: "最多支持三张照片",
                    duration: 1500
                  });
                }else {
                  for (var i = 0,j=imgPic.length; i < results.length; i++,j++) {
                    imgPic[j]=results[i];
                  }
                }
              }, function(error) {
                // error getting photos
              });
          }
          $scope.imgData=imgPic;

          return true;
        }
      });
    };
    $scope.deleteImg=function(img){
      var j;
      var receipt = $ionicPopup.confirm({
        title : '是否删除图片',
        cancelText : '否',
        cancelType : 'button-stable',
        okText : '是'
      });
      receipt.then(function(r){
        if(r){
          for (var i=0;i<$scope.imgData.length;i++){
            if ($scope.imgData[i]==img){
              j=i;
              $scope.imgData.splice(j,1);
            }
          }
        }else{
          console.log('取消');
        }
      });
    };
    function uploadImg(){
      var j=0;
      for (var i=0;i<$scope.imgData.length;i++){
        var canvas = document.createElement('CANVAS');
        var ctx = canvas.getContext('2d');
        var dataURL;
        var img = new Image();
        img.crossOrigin = 'Anonymous';
        img.src = $scope.imgData[i];
        img.onload = function(){
          canvas.height = this.height;
          canvas.width = this.width;
          ctx.drawImage(this,0,0,this.width,this.height);
          var ext = this.src.substring(this.src.lastIndexOf(".")+1).toLowerCase();
          var extendName = this.src.substring(this.src.lastIndexOf("/")+1).toLowerCase();
          dataURL = canvas.toDataURL("image/"+ext);
          $scope.order.pictureInfo.splice(j,0,{fileName:extendName,fileContext:dataURL});
          j++;
        };
      }
    }
    //保存订单
    function  addOrder(){
      $scope.order.goodsInfo.goodsPack=$("#GOODS_PACK option:selected").val();
      $scope.order.deliveryType=$("#DELIVERY_TYPE option:selected").val();
      $scope.order.paymentSwitch=$("#paymentMethod option:selected").val();
      //是否投保
      if ($scope.order.isInsure){
        $scope.order.insureSwitch='0';
      }else {
        $scope.order.insureSwitch='1';
      }
      //是否提货
      if ($scope.order.isPickup){
        $scope.order.pickupSwitch='0';
      }else {
        $scope.order.pickupSwitch='1';
      }
      //是否签单
      if ($scope.order.isReceipt){
        $scope.order.receiptSwitch='0';
      }else {
        $scope.order.receiptSwitch='1';
      }
      if ($scope.order.belongId==''){
        $ionicLoading.show({
          noBackdrop: true,
          template: "请选择物流公司",
          duration: 1500
        });
        $("#save").attr("disabled",false);
      }else if($scope.order.consigneeName==''&&$scope.order.consigneePhone=='') {
        $ionicLoading.show({
          noBackdrop: true,
          template: "请选择收货地址",
          duration: 1500
        });
        $("#save").attr("disabled",false);
      }else if ($scope.order.consignorName==''&&$scope.order.consignorPhone==''){
        $ionicLoading.show({
          noBackdrop: true,
          template: "请选择发货地址",
          duration: 1500
        });
        $("#save").attr("disabled",false);
      }else if ($scope.order.goodsInfo.goodsName==''){
        $ionicLoading.show({
          noBackdrop: true,
          template: "请填写货物名称",
          duration: 1500
        });
        $("#save").attr("disabled",false);
      }else if ($scope.order.goodsInfo.pieces==''){
        $ionicLoading.show({
          noBackdrop: true,
          template: "请填写货物件数",
          duration: 1500
        });
        $("#save").attr("disabled",false);
      }else {
        uploadImg();
        $timeout(function(){
          AddOrder.getAddOrder($scope.order);
        },160);
      }
    }
    $scope.addOrder=function(){
      $("#save").attr("disabled",true);
      addOrder();
      $scope.$on('AddOrder.Updated', function() {
        var result=AddOrder.getResult();
        if (result.success==true){
          $ionicLoading.show({
            noBackdrop: true,
            template: "保存成功",
            duration: 1500
          });
          $("#save").attr("disabled",false);
          $state.go('tab.workbench');
        }else {
          $ionicLoading.show({
            noBackdrop: true,
            template: "保存失败",
            duration: 1500
          });
          $("#save").attr("disabled",false);
        }
      });
    };
    $scope.callPhone = function (mobilePhone) {
      var confirmPopup = $ionicPopup.confirm({
        title:mobilePhone,
        okText:'呼叫',
        cancelText:'取消'
      });
      confirmPopup.then(function(res) {
        if (res) {
          $window.location.href = "tel:" + mobilePhone;
        }else {

        }
      });
    };
  });
